package net.hvacapp.cmvrfforandroid.ui;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.j256.ormlite.table.TableUtils;
import com.mirror.android.common.util.ToastUtils;

import net.hvacapp.cmvrfforandroid.AppManager;
import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.constant.Constant;
import net.hvacapp.cmvrfforandroid.db.DatabaseConfigUtil;
import net.hvacapp.cmvrfforandroid.db.DatabaseHelper;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.model.GetUserProfileDataResp;
import net.hvacapp.cmvrfforandroid.model.LoginDataResp;
import net.hvacapp.cmvrfforandroid.ui.selections.model.GetAreaDataResp;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;
import net.hvacapp.cmvrfforandroid.utils.PreferenceHelper;
import net.hvacapp.cmvrfforandroid.widget.FButton;
import net.hvacapp.cmvrfforandroid.widget.IOSAlertView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.w3c.dom.Text;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录页面
 */
@EActivity(R.layout.activity_login)
public class LoginActivity extends BaseActivity {

    @ViewById(R.id.cet_username)
    EditText mUsernameEt;// 名字输入框
    @ViewById(R.id.cet_password)
    EditText mPasswordEt;// 密码输入框
    @ViewById(R.id.tv_forget)
    TextView mForget;



    @ViewById(R.id.btn_login)
    FButton mLoginBtn;// 登录按钮
    @ViewById(R.id.tv_version)
    TextView mVersionTv;


    private String mUsername = null;// 用户名字
    private String mPassword = null;// 用户密码

    private PreferenceHelper preferenceHelper;// 偏好设置工具类

    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        checkDbVersion();
        initEvent();
    }

    /**
     * 初始化
     */
    @Override
    public void initBoot() {
        preferenceHelper = new PreferenceHelper(context);
    }

    /**
     * 初始化数据
     */
    @Override
    public void initData(Intent intent) {
        mUsername = preferenceHelper.getString(Constant.USERNAME, null);
        mPassword = preferenceHelper.getString(Constant.PASSWORD, null);

        if (!TextUtils.isEmpty(mUsername)) {
            mUsernameEt.setText(mUsername);
            mUsernameEt.setSelection(mUsername.length());
        }

        if (!TextUtils.isEmpty(mPassword)) {
            mPasswordEt.setText(mPassword);
        }

        PackageManager manager;
        PackageInfo info = null;
        manager = context.getPackageManager();
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = "当前版本号：V" + info.versionName;
            mVersionTv.setText(version);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        loadDefaultNation();

    }

    /**
     * 检查数据库版本信息，如果有升级，则更新数据库
     */
    @Background
    void checkDbVersion() {

        int dbVersion = preferenceHelper.getInt(Constant.DB_VERSION, 0);

        if (dbVersion < Constant.DB_VERSION_NUMBER) {
            DatabaseHelper databaseHelper = DatabaseHelper.getInstance(context);
            Class<?>[] classes = DatabaseConfigUtil.classes;
            try {
                for (Class<?> clazz : classes) {
                    TableUtils.dropTable(databaseHelper.getConnectionSource(), clazz, true);
                }
                for (Class<?> clazz : classes) {
                    TableUtils.createTable(databaseHelper.getConnectionSource(), clazz);
                }
                databaseHelper.initDatabase(databaseHelper.getWritableDatabase());

                preferenceHelper.putInt(Constant.DB_VERSION, Constant.DB_VERSION_NUMBER);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void loadDefaultNation() {
        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_DEFAULT_NATION, new HttpCallbackHandle<GetAreaDataResp>() {
            @Override
            public void onSuccess(GetAreaDataResp obj) {
                // 成功
                AppManager.getAppManager().setmDefaultNation(obj.getGetDefaultNationResult());
            }

            @Override
            public void onFailure(String response) {

            }

        });
    }

//    - (void)loadDefaultNation {
//        [HttpClient getWithUrl:HTTP_GET_DEFAULT_NATION param:nil resultClass:[ProvinceData class] success:^(ProvinceData *obj) {
//            self.defaultNation = obj.getDefaultNationResult;
//        } failure:^(NSError *error) {
//            CMLog(@"获取默认国家失败:%@", error);
//        }];
//    }

    private void initEvent() {
        mUsernameEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mUsernameEt.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {

            }
        });

        mForget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //忘记密码
                String username = mUsernameEt.getText().toString().trim();

                if (TextUtils.isEmpty(username)) {
                    ToastUtils.show(LoginActivity.this, "请输入用户名!");
                    return;
                }
                forgetPassword(username);
            }
        });
    }

    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    /**
     * 按钮点击事件
     *
     * @param v
     */
    @Click({R.id.btn_login, R.id.tv_register})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
            /* 友盟用户事件统计 */

                String username = mUsernameEt.getText().toString().trim();
                String password = mPasswordEt.getText().toString().trim();

                if (TextUtils.isEmpty(username)) {
                    showMessage("请输入用户名!");
                    return;
                }

                if (TextUtils.isEmpty(password)) {
                    showMessage("请输入密码!");
                    return;
                }

                mUsername = username;
                mPassword = password;
                systemLogin(mUsername, mPassword);
                break;
            case R.id.tv_register:
//                showMessage("去注册吧");
                startActivity(AnnotationUtil.get(RegisterActivity.class));
                break;
            default:
                break;
        }
    }


    /**
     * 找回密码
     *
     * @param userName 用户名
     */
    private void forgetPassword(final String userName) {
        //参数

        final Dialog progressDlg = createProgressBarDialog(this, "找回密码中...");
        progressDlg.show();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put(
                "userName",
                new String(Base64.encode((userName).getBytes(), Base64.DEFAULT)));


        BasicHttpClient.httpPostAsync(HttpConstant.HTTP_POST_FORGET_PASSWORD, params,
                new HttpCallbackHandle<LoginDataResp>() {
                    @Override
                    public void onSuccess(LoginDataResp obj) {
                        // 成功
                        progressDlg.dismiss();
                        IOSAlertView.showAlertView(LoginActivity.this, "提示", "您的密码已经发送到您注册邮箱，请查收！", "我知道了", null);
                    }

                    @Override
                    public void onFailure(String response) {
                        progressDlg.dismiss();
                        IOSAlertView.showAlertView(LoginActivity.this, "提示", "找回密码失败，请重试！", "我知道了", null);
                    }

                });

    }

    /**
     * 系统登录
     *
     * @param userName 用户名
     * @param password 密码
     */
    private void systemLogin(final String userName, final String password) {
        //参数

        final Dialog progressDlg = createProgressBarDialog(this, "登录中...");
        progressDlg.show();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put(
                "userName",
                new String(Base64.encode((userName).getBytes(), Base64.DEFAULT)));
        params.put("userPassword",
                new String(Base64.encode(password.getBytes(), Base64.DEFAULT)));


        BasicHttpClient.httpPostAsync(HttpConstant.HTTP_POST_LOGIN, params,
                new HttpCallbackHandle<LoginDataResp>() {
                    @Override
                    public void onSuccess(LoginDataResp obj) {
                        // 成功
                        progressDlg.dismiss();
                        preferenceHelper.putString(Constant.USERNAME, userName);
                        preferenceHelper.putString(Constant.PASSWORD, password);
                        AccountManager.getInstance().setToken(obj.getLoginResult());
                        loadUserProfileData();
                        //跳转到主页面
                        startActivity(AnnotationUtil.get(MainTabBarActivity.class));
                    }

                    @Override
                    public void onFailure(String response) {
                        progressDlg.dismiss();
                        showMessage("用户名或者密码错误！");
                    }

                });

    }


    /***
     * 获取用户的账户信息
     */
    private void loadUserProfileData() {
        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_USER_PROFILE, AccountManager.getInstance().getToken(), new HttpCallbackHandle<GetUserProfileDataResp>() {
            @Override
            public void onSuccess(GetUserProfileDataResp obj) {
                // 成功
                AccountManager.getInstance().setUserInfo(obj.getGetUserProfileResult());
            }

            @Override
            public void onFailure(String response) {

            }

        });
    }


}
